<template>
  <el-main>
    <!-- 搜索栏 -->
    <el-form :model="searchParm" :inline="true" size="default">
      <el-form-item>
        <el-select
          v-model="searchParm.type"
          class="m-2"
          placeholder="请选择类型"
          size="default"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-input
          placeholder="请填写关键字"
          v-model="searchParm.title"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="searchBtn" icon="Search">搜索</el-button>
        <el-button icon="Close" @click="resetBtn" type="danger" plain
          >重置</el-button
        >
        <el-button icon="Plus" type="primary" @click="addBtn">新增</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格数据 -->
    <el-table :height="tableHeight" :data="tableList" border stripe>
      <el-table-column prop="image" label="图片" align="center">
        <template #default="scope">
          <el-image
            v-if="scope.row.image"
            style="width: 100px; height: 60px"
            :src="scope.row.image"
          />
        </template>
      </el-table-column>
      <el-table-column label="标题" prop="title"></el-table-column>
      <el-table-column label="简介" prop="titleDesc"></el-table-column>
      <el-table-column label="类型" prop="title">
        <template #default="scope">
          <el-tag type="success" v-if="scope.row.type == '0'" size="default"
            >失物</el-tag
          >
          <el-tag type="danger" v-if="scope.row.type == '1'" size="normal"
            >招领</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="status">
        <template #default="scope">
          <el-tag type="danger" v-if="scope.row.status == '0'" size="default"
            >{{ scope.row.type=='0' ? '未找回' : '未认领' }}</el-tag
          >
          <el-tag type="success" v-if="scope.row.status == '1'" size="normal"
            >{{ scope.row.type=='1' ? '已找回' : '已认领' }}</el-tag
          >
        </template>
      </el-table-column>
      <el-table-column label="认领人" prop="person"></el-table-column>
      <el-table-column label="认领人电话" prop="phone"></el-table-column>
      <el-table-column label="创建时间" prop="cteateTime"></el-table-column>
      <el-table-column label="操作" align="center" width="320">
        <template #default="scope">
          <el-button
            type="primary"
            icon="Edit"
            size="default"
            @click="editBtn(scope.row)"
            >编辑</el-button
          >
          <el-button
            type="success"
            icon="Edit"
            size="default"
            @click="getBtn(scope.row)"
            >
            认领
            </el-button
          >
          <el-button
            type="danger"
            icon="Delete"
            size="default"
            @click="deleteBtn(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- //分页 -->
    <el-pagination
      @size-change="sizeChange"
      @current-change="currentChange"
      :current-page.sync="searchParm.currentPage"
      :page-sizes="[10, 20, 40, 80, 100]"
      :page-size="searchParm.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="searchParm.total"
      background
    >
    </el-pagination>
  </el-main>
  <!-- 新增弹框 -->
  <SysDialog
    :title="dialog.title"
    :width="dialog.width"
    :visible="dialog.visible"
    :height="dialog.height"
    @OnClose="onClose"
    @onConfirm="commit"
  >
    <template v-slot:content>
      <el-form
        :model="addModel"
        ref="addRef"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="default"
      >
        <el-form-item prop="title" label="标题:">
          <el-input
            v-model="addModel.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item prop="titleDesc" label="简介:">
          <el-input
            v-model="addModel.titleDesc"
            placeholder="请输入简介"
          ></el-input>
        </el-form-item>
        <el-form-item prop="image" label="图片:">
          <UploadImage
            @getImg="getImg"
            ref="uploadRef"
            :fileList="fileList"
            :oldUrl="oldUrl"
          ></UploadImage>
        </el-form-item>
        <el-form-item prop="content" label="详情">
          <div v-if="dialog.visible" style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              :mode="mode"
            />
            <Editor
              style="height: 300px; overflow-y: hidden"
              v-model="valueHtml"
              :defaultConfig="editorConfig"
              :mode="mode"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item prop="type" label="类型:">
          <el-radio-group v-model="addModel.type">
            <el-radio :label="'0'">失物</el-radio>
            <el-radio :label="'1'">招领</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </template>
  </SysDialog>
  <!-- 认领弹框 -->
  <el-dialog
    v-model="centerDialogVisible"
    title="认领记录"
    width="30%"
    align-center
  >
    <span>
      <el-form :model="personModel" ref="personRef" :rules="personrules" label-width="100px" :inline="false" size="normal">
        <el-form-item prop="person" label="认领人">
          <el-input v-model="personModel.person"></el-input>
        </el-form-item>
        <el-form-item prop="phone" label="认领人电话">
          <el-input v-model="personModel.phone"></el-input>
        </el-form-item>
      </el-form>
    </span>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="danger" @click="personCancel">取消</el-button>
        <el-button type="primary" @click="personCommit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import SysDialog from "@/components/SysDialog.vue";
import useDialog from "@/hooks/useDialog";
import UploadImage from "@/components/UploadImage.vue";
import { ElMessage, FormInstance, UploadUserFile } from "element-plus";
import { NewType } from "@/type/BaseType";
import useEditor from "@/hooks/useEditor";
import { addApi, getListApi, Lost, editApi, deleteApi,claimApi } from "@/api/lost/index";
import useInstance from "@/hooks/useInstance";
const { global } = useInstance();
//认领弹框显示影藏
const centerDialogVisible = ref(false)
const personRef = ref();
//认领表单对象
const personModel = reactive({
  lostId:'',
  person:'',
  phone:''
})
const personrules = reactive({
  person: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写认领人",
    },
  ],
  phone: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写认领人电话",
    },
  ]
})
//认领
const getBtn = (row: Lost)=>{
  if(row.status == '1'){
    ElMessage.warning('该物品已经认领，不要重复认领!')
    return;
  }
  console.log(row)
  personModel.lostId = row.lostId;
  // personModel.person = '';
  // personModel.phone = '';
  centerDialogVisible.value = true;
  personRef.value.resetFields()
}
//认领记录提交
const personCommit = ()=>{
 personRef.value.validate(async(valid:boolean)=>{
  console.log(valid)
  if(valid){
    let res = await claimApi(personModel)
    if(res && res.code == 200){
      getList()
      centerDialogVisible.value = false;
    }
  }
 })
}
const personCancel = ()=>{
  centerDialogVisible.value = false;
}
//文本编辑器
const {
  editorRef,
  handleCreated,
  editorConfig,
  valueHtml,
  toolbarConfig,
  mode,
} = useEditor();
//图片上传ref属性
const uploadRef = ref();
//图片回显的数据
const fileList = ref<Array<UploadUserFile>>([]);
//图片默认的url
const oldUrl = ref<Array<{ url: string }>>([]);
const imgUrl = ref<Array<{ url: string }>>([]);
//表单ref属性
const addRef = ref<FormInstance>();

//弹框属性
const { dialog, onClose, onShow } = useDialog();
//搜索表单
const searchParm = reactive({
  currentPage: 1,
  pageSize: 10,
  title: "",
  type: "",
  total: 0,
});
const options = [
  {
    value: "0",
    label: "失物",
  },
  {
    value: "1",
    label: "招领",
  },
];
const tags = ref("");
//新增
const addBtn = () => {
  tags.value = "0";
  dialog.title = "新增";
  dialog.height = 400;
  dialog.width = 800;
  imgUrl.value = [];
  oldUrl.value = [];
  fileList.value = [];
  valueHtml.value = "";
  onShow();
  //清空表单
  addRef.value?.resetFields();
};
//新增绑定的对象
const addModel = reactive({
  lostId: "",
  title: "",
  titleDesc: "",
  content: "",
  type: "",
  image: "",
  status:''
});
//编辑
const editBtn = (row: Lost) => {
  tags.value = "1";
  console.log(row);
  dialog.title = "编辑";
  dialog.height = 400;
  dialog.width = 800;
  imgUrl.value = [];
  oldUrl.value = [];
  fileList.value = [];
  valueHtml.value = "";
  //清空表单
  addRef.value?.resetFields();
  onShow();
  //设置回显的数据
  nextTick(() => {
    Object.assign(addModel, row);
    //图片回显
    if (addModel.image) {
      //转换为数组
      let imgs = addModel.image.split(",");
      for (let i = 0; i < imgs.length; i++) {
        let img = { name: "", url: "" };
        img.name = imgs[i];
        img.url = imgs[i];
        fileList.value.push(img);
        oldUrl.value.push({ url: imgs[i] });
      }
    }
    //设置编辑器的数据
    valueHtml.value = addModel.content;
  });
};
//删除
const deleteBtn = async (row: Lost) => {
  console.log(row);
  const confirm = await global.$myconfirm("确定删除该数据吗?");
  if (confirm) {
    let res = await deleteApi(row.lostId);
    if (res && res.code == 200) {
      ElMessage.success(res.msg);
      getList();
    }
  }
};

//页容量改变时触发
const sizeChange = (size: number) => {
  searchParm.pageSize = size;
  getList();
};
//页数改变时触发
const currentChange = (page: number) => {
  searchParm.currentPage = page;
  getList();
};
watch(
  () => valueHtml.value,
  (value) => {
    addModel.content = value;
  }
);
//表单验证规则
const rules = reactive({
  title: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写标题",
    },
  ],
  titleDesc: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写简介",
    },
  ],
  content: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请填写内容",
    },
  ],
  image: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请上传图片",
    },
  ],
  type: [
    {
      required: true,
      trigger: ["blur", "change"],
      message: "请选择类型",
    },
  ],
});
//图片上传返回
const getImg = (img: NewType) => {
  console.log(img);
  imgUrl.value = oldUrl.value.concat(img.newImgUrl);
  if (img.deleteUrl.length > 0) {
    //删除数据
    let newArr = imgUrl.value.filter(
      (x) => !img.deleteUrl.some((item) => x.url == item.url)
    );
    imgUrl.value = newArr;
  }
  let url = "";
  //图片地址转为逗号分隔的字符串  aa.png,bb.png,
  for (let k = 0; k < imgUrl.value.length; k++) {
    url = url + imgUrl.value[k].url + ",";
  }
  //去掉字符串最后一个逗号
  addModel.image = url.substring(0, url.lastIndexOf(","));
};
//表单提交
const commit = () => {
  addRef.value?.validate(async (valid) => {
    if (valid) {
      console.log(addModel);
      let res = null;
      if (tags.value == "0") {
        res = await addApi(addModel);
      } else {
        res = await editApi(addModel);
      }
      if (res && res.code == 200) {
        ElMessage.success(res.msg);
        onClose();
        getList();
        //清空图片
        uploadRef.value.clearimg();
      }
    }
  });
};
//表格数据
const tableList = ref([]);
//查询列表数据
const getList = async () => {
  let res = await getListApi(searchParm);
  if (res && res.code == 200) {
    tableList.value = res.data.records;
    console.log(tableList.value);
    searchParm.total = res.data.total;
  }
};
//搜索
const searchBtn = () => {
  getList();
};
//重置
const resetBtn = () => {
  searchParm.currentPage = 1;
  searchParm.title = "";
  searchParm.type = "";
  getList();
};
//表格高度
const tableHeight = ref(0);
onMounted(() => {
  getList();
  nextTick(() => {
    tableHeight.value = window.innerHeight - 230;
  });
});
</script>

<style scoped></style>
